package com.reform.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JwtToken 工具类
 *
 * @author mortale
 * @since 2021/6/22 12:38
 *
 */
@Component
public class JwtTokenUtil {

    private static final String CLAIM_KEY_GH="gh";
    private static final String CLAIM_KEY_NAME="name";
    private static final String CLAIM_KEY_TYPE="type";
    private static final String CLAIM_KEY_CREATED="created";
    private static final String CLAIM_KEY_UUID="uuid";
    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Long expiration;

    /**
     * 根据用户信息生成token
     * @param gh
     * @param name
     * @param type
     * @return
     */
    public String generateToken(String gh,String name,Integer type,String uuid){
        Map<String,Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_GH,gh);
        claims.put(CLAIM_KEY_NAME,name);
        claims.put(CLAIM_KEY_TYPE,type);
        claims.put(CLAIM_KEY_CREATED,new Date());
        claims.put(CLAIM_KEY_UUID,uuid);
        Date date = generateExpirationDate();
        return generateToken(claims);
    }

    /**
     * 从token中获取工号
     * @param token
     * @return
     */
    public String getGHFromToken(String token){
        String gh;
        try {
            Claims claims = getClaimsFormToken(token);
            gh = claims.get(CLAIM_KEY_GH,String.class);
        } catch (Exception e){
            gh = null;
        }
        return gh;
    }

    /**
     * 从token中获取姓名
     * @param token
     * @return
     */
    public String getNameFromToken(String token){
        String name;
        try {
            Claims claims = getClaimsFormToken(token);
            name = claims.get(CLAIM_KEY_NAME,String.class);
        } catch (Exception e){
            name = null;
        }
        return name;
    }

    /**
     * 从token中获取类型
     * @param token
     * @return
     */
    public Integer getTypeFromToken(String token){
        Integer type;
        try {
            Claims claims = getClaimsFormToken(token);
            type = claims.get(CLAIM_KEY_TYPE,Integer.class);
        } catch (Exception e){
            type = null;
        }
        return type;
    }

    /**
     * 从token中获取UUID
     * @param token
     * @return
     */
    public String getUUIDFromToken(String token){
        String uuid;
        try {
            Claims claims = getClaimsFormToken(token);
            uuid = claims.get(CLAIM_KEY_UUID,String.class);
        } catch (Exception e){
            uuid = null;
        }
        return uuid;
    }

    /**
     * 从token中获取荷载
     * @param token
     * @return
     */
    private Claims getClaimsFormToken(String token){
        Claims claims = null;
        try {
            claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (Exception e){
            e.printStackTrace();
        }

        return claims;
    }

    /**
     * 验证token是否有效
     * @param token
     * @return
     */
    public boolean validateToken(String token){
        return isTokenExpired(token);
    }

    /**
     * 判断token是否失效
     * @param token
     * @return
     */
    private boolean isTokenExpired(String token) {
        try{
            Claims claims = getClaimsFormToken(token);
            Date expireDate = getExpiredDateFromToken(token);
            return !expireDate.before(new Date());
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 判断token是否可以被刷新
     * @param token
     * @return
     */
    public boolean canRefresh(String token){
        return !isTokenExpired(token);
    }

    /**
     * 刷新token
     * @param token
     * @return
     */
    public String refreshToken(String token){
        Claims claims = getClaimsFormToken(token);
        claims.put(CLAIM_KEY_CREATED,new Date());
        return generateToken(claims);
    }

    /**
     * 从token中获取过期时间
     * @param token
     * @return
     */
    private Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFormToken(token);
        Date expiration = claims.getExpiration();
        return expiration;
    }

    /**
     * 根据荷载生成Jwt token
     * @param claims
     * @return
     */
    private String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512,secret)
                .compact();
    }

    /**
     * 生成token失效时间
     * @return token失效时间
     */
    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }


}
